package com.tjshop.android.model;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;

import com.tjshop.android.R;
import com.tjshop.android.GoodsListActivity;
import com.tjshop.android.adapter.CategoryAdapter;
import com.tjshop.android.fragment.AbstractItem;
import com.tjshop.android.model.tj.HomeData;

public class CategoriesItem extends AbstractItem {
	private HomeData homeData;
	private LayoutInflater mInflater;
	private Context context;

	public CategoriesItem(Context mContext, HomeData homeData,
			LayoutInflater mInflater) {
		super(mContext);
		this.homeData = homeData;
		this.mInflater = mInflater;
		this.context = mContext;
	}

	@Override
	public View inflateSelf(final LayoutInflater inflater) {
		return inflater.inflate(
				R.layout.inc_activity_main_fragment_home_item_categories, null);
	}

	@Override
	public String getType() {
		return "item_categories";
	}

	@Override
	public void fillViewWithData(final View view) {
		initCategories(view);
	}

	/**
	 * 初始化分类。
	 * 
	 * @param container
	 */
	private void initCategories(final View container) {

		CategoryAdapter adapter = new CategoryAdapter(context,
				homeData.getCategoryList(), mInflater);
		// 获得GridView实例并进行设置
		GridView gv = (GridView) container
				.findViewById(R.id.fragment_home_categories);
		gv.setAdapter(adapter); // 为GridView设置数据源
		gv.setOnItemClickListener(new ItemClickListener());
	}

	// 当AdapterView被单击(触摸屏或者键盘)，则返回的Item单击事件
	class ItemClickListener implements AdapterView.OnItemClickListener {
		public void onItemClick(AdapterView<?> arg0,// The AdapterView where the
													// click happened
				View arg1,// The view within the AdapterView that was clicked
				int arg2,// The position of the view in the adapter
				long arg3// The row id of the item that was clicked
		) {
			// GlobeVars.mTabHost.setCurrentTab(1);
			// GlobeVars.CouponCategory = homeCouponList.get(arg2).getTitle();

			Bundle b = new Bundle();
			b.putString("id", arg2 == 7 ? "0" : homeData.getCategoryList()
					.getItems().get(arg2).getId());

			// TODO 打开CategoryDetailActivity，其实应该传递一些必要的参数过去
			Intent intent = new Intent();
			intent.putExtras(b);
			intent.setClass(context, GoodsListActivity.class);
			context.startActivity(intent);
		}
	}
}
